package com.shiqupad.order.activity;

import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.shiqupad.order.fragment.CallFragment;
import com.shiqupad.order.fragment.OrderFragment;
import com.shiqupad.order.fragment.TableScanFragment;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.com.dreamtouch.common.DTLog;
import cn.com.dreamtouch.magicbox_common.util.CommonConstant;
import cn.com.dreamtouch.magicbox_general_ui.activity.MBBaseActivity;
import cn.com.dreamtouch.magicbox_general_ui.ui.ActionSheetDialog;
import cn.com.dreamtouch.magicbox_general_ui.util.RxBusUtil;
import cn.com.dreamtouch.magicbox_general_ui.util.Utils;
import cn.com.dreamtouch.magicbox_http_client.network.model.LoginResponse;
import cn.com.dreamtouch.magicbox_http_client.network.model.RxEvent;
import cn.com.dreamtouch.magicbox_repository.datasource.local.UserLocalData;

import com.shiqupad.order.R;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import rx.functions.Action1;

public class MainActivity extends MBBaseActivity {
    private static final String TAG = "MainActivity";
    @Bind(R.id.frame_content)
    FrameLayout frameContent;
    @Bind(R.id.ic_main_sliding_left)
    ImageView ivSlidingLeft;

    TextView tvExit;
    SimpleDraweeView sdvSlidingUser;
    RadioButton rbSlidingScan;
    RadioButton rbSlidingOrder;
    RadioButton rbCall;
    RadioGroup rgSliding;
    LinearLayout llSlidingExit;


    SlidingMenu menu;
    private final String SCAN_TAG = "SCAN";//堂食
    private final String ORDER_TAG = "ORDER";//订单
    private final String CALL_TAG = "CALL";//叫号

    private final String CHECK_TAG = "checkedFragment";

    String checkedFragmentTag;
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(CommonConstant.Args.NEW_NOTIFY)) {

                RxBusUtil.getDefault().post(new RxEvent(CommonConstant.OpertionType.PUSH_MESSAGE
                        , CommonConstant.OpertionType.PUSH_MESSAGE));
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        recieveEvent();
    }

    private void recieveEvent() {
        RxBusUtil.getDefault().toObservable(RxEvent.class).subscribe(new Action1<RxEvent>() {
            @Override
            public void call(RxEvent rxEvent) {
                int flag = rxEvent.getFlag();
                switch (flag) {
                    case CommonConstant.OpertionType.WAIT_CONFIRM_ORDER:
                        switchToOrder();
                        break;

                    case CommonConstant.OpertionType.CALL_SUCCESS:
                        switchToScan();
                        break;

                    case CommonConstant.OpertionType.PAY_SUCCESS:
                        switchToScan();
                        break;
                }
            }
        });
    }

    private void switchToOrder() {
        rbCall.setChecked(false);
        rbSlidingScan.setChecked(false);
        rbSlidingOrder.setChecked(true);
        Fragment orderFragment;
        if (getSupportFragmentManager().findFragmentByTag(ORDER_TAG) == null)
            orderFragment = OrderFragment.newInstance();
        else
            orderFragment = getSupportFragmentManager().findFragmentByTag(ORDER_TAG);
        switchContent(orderFragment, ORDER_TAG);
    }

    private void switchToScan() {
        rbSlidingScan.setChecked(true);
        rbCall.setChecked(false);
        rbSlidingOrder.setChecked(false);
        Fragment tableScanFragment;
        if (getSupportFragmentManager().findFragmentByTag(SCAN_TAG) == null)
            tableScanFragment = TableScanFragment.newInstance();
        else
            tableScanFragment = getSupportFragmentManager().findFragmentByTag(SCAN_TAG);
        switchContent(tableScanFragment, SCAN_TAG);
    }



    private void setMenu() {
        menu.setMode(SlidingMenu.LEFT);
        // 设置触摸屏幕的模式
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
        // menu.setShadowWidthRes(25);
        menu.setShadowDrawable(R.color.bg_color_white);

        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();

        if (Utils.isPad(this)) {
            // 设置滑动菜单视图的宽度
            menu.setBehindOffset((int) (0.90 * width));
        } else {
            // 设置滑动菜单视图的宽度
            menu.setBehindOffsetRes(R.dimen.sliding_menu_offset);
        }
        // 设置渐入渐出效果的值
        menu.setFadeDegree(0.35f);
        //把滑动菜单添加进所有的Activity中，可选值SLIDING_CONTENT， SLIDING_WINDOW
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        //为侧滑菜单设置布局
        menu.setMenu(R.layout.sliding_menu_left);

    }

    @Override
    protected void initVariables() {
        super.initVariables();


    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        menu = new SlidingMenu(this);
        setMenu();
        rbSlidingScan = findViewById(R.id.rb_sliding_scan);
        rbSlidingOrder = findViewById(R.id.rb_sliding_order);
        tvExit = findViewById(R.id.sling_exit_tv);

        rbCall = findViewById(R.id.rb_call);
        rgSliding = findViewById(R.id.rg_sliding);
        llSlidingExit = findViewById(R.id.ll_sliding_exit);
        initFragment(savedInstanceState);
        tvExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exitDialogShow();

            }
        });
        setBasicStyleNotification();

        LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CommonConstant.Args.NEW_NOTIFY);
        broadcastManager.registerReceiver(receiver, intentFilter);
    }

    private void exitDialogShow() {
        if (!isFinishing()) {
            new ActionSheetDialog(MainActivity.this).builder()
                    .setTitle("确认退出吗？")
                    .addSheetItem("确定", ActionSheetDialog.SheetItemColor.Red, new ActionSheetDialog.OnSheetItemClickListener() {
                        @Override
                        public void onClick(int which) {
                            UserLocalData.getInstance(MainActivity.this).clear();
                            // 跳转到登录界面
                            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            JPushInterface.cleanTags(MainActivity.this, 1);
                        }
                    })
                    .setCancelable(true)
                    .show();

        }
    }

    private void initFragment(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            //初始化第一个fragment,我的e家页面
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(R.id.frame_content, new TableScanFragment(), SCAN_TAG).commitAllowingStateLoss();
            checkedFragmentTag = SCAN_TAG;
            rbSlidingScan.setChecked(true);
            rbCall.setChecked(false);
            rbSlidingOrder.setChecked(false);

        } else {
            DTLog.i(TAG, "have savedInstanceState");
            Fragment scanTableFt = getSupportFragmentManager().findFragmentByTag(SCAN_TAG);
            Fragment orderFt = getSupportFragmentManager().findFragmentByTag(ORDER_TAG);
            Fragment callFt = getSupportFragmentManager().findFragmentByTag(CALL_TAG);

            TableScanFragment tableScanFragment = null;
            OrderFragment orderFragment = null;
            CallFragment callFragment = null;


            if (scanTableFt instanceof TableScanFragment) {
                tableScanFragment = (TableScanFragment) scanTableFt;
            }
            if (orderFt instanceof OrderFragment) {
                orderFragment = (OrderFragment) orderFt;
            }
            if (callFt instanceof CallFragment) {
                callFragment = (CallFragment) callFt;
            }

            checkedFragmentTag = savedInstanceState.getString(CHECK_TAG);
            if (getSupportFragmentManager().findFragmentByTag(checkedFragmentTag) == null) {
                DTLog.i(TAG, "showingFragment is null");
            } else {
                DTLog.i(TAG, "showingFragment is " + checkedFragmentTag);
                FragmentManager fm = getSupportFragmentManager();
                //还原隐藏的fragment状态
                FragmentTransaction ft = fm.beginTransaction();
                if (tableScanFragment != null && !SCAN_TAG.equals(checkedFragmentTag)) {
                    ft.hide(tableScanFragment);
                }
                if (orderFragment != null && !ORDER_TAG.equals(checkedFragmentTag)) {
                    ft.hide(orderFragment);
                }
                if (callFragment != null && !CALL_TAG.equals(checkedFragmentTag)) {
                    ft.hide(callFragment);
                }

                ft.show(getSupportFragmentManager().findFragmentByTag(checkedFragmentTag)).commit();
            }
        }
        setRadioBtnEvent();

    }

    private void setRadioBtnEvent() {
        rbSlidingScan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    Fragment myTableFragment;
                    if (getSupportFragmentManager().findFragmentByTag(SCAN_TAG) == null)
                        myTableFragment = TableScanFragment.newInstance();
                    else
                        myTableFragment = getSupportFragmentManager().findFragmentByTag(SCAN_TAG);
                    switchContent(myTableFragment, SCAN_TAG);
                }
            }
        });

        rbSlidingOrder.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    Fragment orderFragment;
                    if (getSupportFragmentManager().findFragmentByTag(ORDER_TAG) == null)
                        orderFragment = OrderFragment.newInstance();
                    else
                        orderFragment = getSupportFragmentManager().findFragmentByTag(ORDER_TAG);
                    switchContent(orderFragment, ORDER_TAG);
                }
            }
        });

        rbCall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked) {
                    Fragment callFragment;
                    if (getSupportFragmentManager().findFragmentByTag(CALL_TAG) == null)
                        callFragment = CallFragment.newInstance();
                    else
                        callFragment = getSupportFragmentManager().findFragmentByTag(CALL_TAG);
                    switchContent(callFragment, CALL_TAG);
                }
            }
        });


    }

    public void switchContent(Fragment to, String tag) {
        if (to == null) {
            DTLog.e("MainActivity", "switchContent to " + tag + " fail");
            return;
        } else if (getSupportFragmentManager().findFragmentByTag(checkedFragmentTag) == null) {
            DTLog.e("MainActivity", "switchContent checkedFragmentTag " + checkedFragmentTag + " fail");
            return;
        }
        if (getSupportFragmentManager().findFragmentByTag(checkedFragmentTag) != to) {

            FragmentManager fm = getSupportFragmentManager();
            //添加渐隐渐现的动画
            FragmentTransaction ft = fm.beginTransaction();

            if (!to.isAdded()) {    // 先判断是否被add过
                ft.hide(getSupportFragmentManager().findFragmentByTag(checkedFragmentTag)).add(R.id.frame_content, to, tag).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
                fm.executePendingTransactions();
            } else {
                ft.hide(getSupportFragmentManager().findFragmentByTag(checkedFragmentTag)).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
                fm.executePendingTransactions();
                if (tag.equals(SCAN_TAG)) {
                    TableScanFragment fragment = (TableScanFragment) getSupportFragmentManager().
                            findFragmentByTag(SCAN_TAG);
                    fragment.refreshTabData();//切换时刷新数据
                } else if (tag.equals(ORDER_TAG)) {
                    OrderFragment fragment = (OrderFragment) getSupportFragmentManager().findFragmentByTag(ORDER_TAG);
                    fragment.refreshTabData();//切换时刷新数据
                } else if (tag.equals(CALL_TAG)) {
                    CallFragment fragment = (CallFragment) getSupportFragmentManager().findFragmentByTag(CALL_TAG);
                    fragment.refreshTabData();//切换时刷新数据
                }
                RxBusUtil.getDefault().post(new RxEvent(CommonConstant.OpertionType.SWITCH_TABLE,
                        CommonConstant.OpertionType.SWITCH_TABLE));
            }
            checkedFragmentTag = tag;

        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        DTLog.i(TAG, "onSaveInstanceState");
        String tag = "";//记录选中的fragment
        if (rbSlidingScan.isChecked()) {
            tag = SCAN_TAG;
        } else if (rbSlidingOrder.isChecked()) {
            tag = ORDER_TAG;
        } else if (rbCall.isChecked()) {
            tag = CALL_TAG;
        }
        outState.putString(CHECK_TAG, tag);
    }

    @Override
    protected void loadData() {
        super.loadData();
    }

    LoginResponse.Data data;


    @OnClick({R.id.ic_main_sliding_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ic_main_sliding_left:
                if (!menu.isMenuShowing()) {
                    menu.toggle();
                }
                break;


        }
    }

    private void setBasicStyleNotification() {
        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(this.getApplicationContext());
        builder.statusBarDrawable = R.drawable.jpush_notification_icon;
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;  //设置为自动消失和呼吸灯闪烁;  //设置为点击后自动消失
        builder.notificationDefaults = Notification.DEFAULT_SOUND
                | Notification.DEFAULT_VIBRATE
                | Notification.DEFAULT_LIGHTS;
        ;  //设置为铃声（ Notification.DEFAULT_SOUND）或者震动（ Notification.DEFAULT_VIBRATE）
        JPushInterface.setPushNotificationBuilder(1, builder);
    }
}
